﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace FileUploader.Web
{
    /// <summary>
    /// Summary description for reciever
    /// </summary>
    public class reciever : IHttpHandler
    {
        /// <summary>
        /// Process the request
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.HttpMethod.ToUpper() != "POST") return;
            string filename = context.Request.Headers["filename"];
            string gid = context.Request.Headers["gid"];
            long Length = long.Parse(context.Request.Headers["length"]);
            long Position = long.Parse(context.Request.Headers["position"]);

            string FilePath = context.Server.MapPath("~/App_Data/" + gid + filename);
            Stream input = context.Request.InputStream;
            FileStream fs;
            if (Position == 0)
            {
                fs = File.Create(FilePath);
            }
            else
            {
                fs = File.Open(FilePath, FileMode.Append, FileAccess.Write);
            }
            
            SaveFile(input, fs);
            fs.Close();

            string fnkey = "fu_" + gid + "_FileName";
            string flkey = "fu_" + gid + "_length";
            string tnkey = "fu_" + gid + "_completed";
            //update status of the request
            context.Application[fnkey] = filename;
            context.Application[flkey] = Length;
            context.Application[tnkey] = Position + input.Length;

            context.Response.ContentType = "text/html";
            context.Response.Write(input.Length);

        }
        /// <summary>
        /// Save stream to a fileStream
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="fs"></param>
        private void SaveFile(Stream stream, FileStream fs)
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                fs.Write(buffer, 0, bytesRead);
            }
        }
        /// <summary>
        /// The page is not re-usable, because it is changing constantly
        /// </summary>
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}